import request from '@/utils/request'
import { LOGIN, LOGOUT } from '@/store/actionTypes'
import { removeToken, setToken } from '@/utils/storage'

export const login = payload => {
  // store 在调用这个函数时回传入一个 dispatch 函数
  return async (dispatch) => {
    console.log('action',`我携带的参数是`,payload);

    const res = await request({
      method: 'Post',
      url: '/authorizations',
      data: payload
    })

    // 持久化存储
    setToken(res.data.token)

    // dispatch 调用时底层会通知 reducers 根据 type 执行对应 action
    dispatch({
      type: LOGIN,
      payload: res.data.token
    })
  }
}

export const logout = ()=>{
  return (dispatch)=>{
    // 清除本地 token 
    removeToken()
    dispatch({
      type:LOGOUT
    })
  }
}